package wo.department.service.impl;

import javax.annotation.Resource;
import javax.transaction.Transactional;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.ExampleMatcher.GenericPropertyMatchers;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;

import wo.department.dto.PositionDto;
import wo.department.po.Position;
import wo.department.repository.PositionRepository;
import wo.department.service.PositionService;
import wo.common.entity.WoPage;
import wo.common.util.WoUtil;

/**
 * PO实体Position对应的Service接口实现类.
 * @author cailei
 */
@Service
@Transactional
public class PositionServiceImpl implements PositionService {

	/**
	 * 使用日志打印框架.
	 */
	private final static Logger LOG = LogManager.getLogger(PositionServiceImpl.class);

	/**
	 * 注入PositionRepository.
	 */
	@Resource // @Autowired
	private PositionRepository positionRepository;

	/**
	 * DataTable获取职务列表数据.
	 * @param start 当前页开始索引,从0开始
	 * @param length 当前页最大行数
	 * @param searchContent 查询内容
	 * @param dir 排序方式
	 * @return
	 */
	@Override
	public WoPage<PositionDto> getPageData(Long start, Long length, String searchContent, String dir) {
		// 从dao获取数据
		Pageable pageInput = PageRequest.of(start.intValue() / length.intValue(), length.intValue()
			 );
		Page<Position> pageData = null;
		if (WoUtil.isEmpty(searchContent)) {
			pageData = positionRepository.findAll(pageInput);
		} else {
			pageData = positionRepository.findAllBynameLike("%" + searchContent + "%", pageInput);
		}
		// 将PO转化为DTO
		WoPage<PositionDto> pr = PositionDto.getPageData(pageData.getContent(), pageData.getTotalElements());
		return pr;
	}

	/**
	 * 创建职务
	 * @param dto
	 */
	@Override
	public void create(PositionDto dto) {
		Position po = dto.createPO();
		positionRepository.save(po);
	}

	/**
	 * 根据id获取职务数据
	 * @param id
	 * @return
	 */
	@Override
	public PositionDto getById(String id) {
		Position po = positionRepository.findById(id).get();
		return new PositionDto (po);
	}

	/**
	 * 修改职务
	 * @param dto
	 */
	@Override
	public void update(PositionDto dto) {
		Position po = positionRepository.findById(dto.getId()).get();
		dto.updatePO(po);
	}

	/**
	 * 根据id数组删除一个或者多个职务
	 * @param id
	 */
	@Override
	public void delete(String[] id) {
		positionRepository.deleteByIdIn(id);
	}

}
